package com.up.vms.interfaces.rest.intercepters;

import com.alibaba.fastjson.JSONObject;
//import com.up.vms.application.authenticate.RedisTokenManager;
//import com.up.vms.domain.member.enums.MemberStatus;
//import com.up.vms.domain.module.MemberDTO;
import com.up.vms.infrastructure.annotations.AuthManager;
import com.up.vms.infrastructure.cache.RedisCacheManager;
import com.up.vms.infrastructure.constants.EmpAPIConstants;
import com.up.vms.infrastructure.util.CommonUtils;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.security.auth.message.AuthException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * Token鉴权拦截器
 * Created by wangshd on 2018/12/4.
 */
@Component
@NoArgsConstructor
@Slf4j
public class TokenAuthenticationInterceptor extends HandlerInterceptorAdapter {

//    @Autowired
//    RedisTokenManager tokenManager;

//    @Autowired
//    RedisCacheManager redisCacheManager;

    //鉴权失败后返回的错误信息，默认为401 unauthorized
    private String unauthorizedErrorMessage = "401 unauthorized";

    //鉴权失败后返回的HTTP错误码，默认为401
    private int unauthorizedErrorCode = HttpServletResponse.SC_UNAUTHORIZED;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        AuthManager annotation;
        if (handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(AuthManager.class);
        } else {
            return true;
        }

        //如果有@AuthManager注解，则验证token
        if (annotation == null) {
            return true;
        }

        return this.initUserSession(request, response);
    }

    private boolean initUserSession(HttpServletRequest request, HttpServletResponse response) throws AuthException{

        //获取用户凭证
        String token = request.getHeader(EmpAPIConstants.USER_TOKEN);
        //For local testing
        //String token = "318ccdfe35954caa84a7d7e4a6cf4027";
        log.info("token is {}", token);

        //token凭证为空
        if (StringUtils.isBlank(token)) {
            JSONObject jsonObject = new JSONObject();

            PrintWriter out = null;
            try {
                response.setStatus(unauthorizedErrorCode);
                response.setContentType(MediaType.APPLICATION_JSON_VALUE);

                jsonObject.put("code", ((HttpServletResponse) response).getStatus());
                jsonObject.put("message", HttpStatus.UNAUTHORIZED);
                out = response.getWriter();
                out.println(jsonObject);
                return false;
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (null != out) {
                    out.flush();
                    out.close();
                }
            }
        }

        log.info("TokenAuthenticationInterceptor：current token is {}", token);
        // todo 商户登录后token处理
//        MemberDTO member = tokenManager.getUserInfoByToken(token);
//        log.info("TokenAuthenticationInterceptor：current member is {}", JSONObject.toJSONString(member));
//        if (CommonUtils.isNotNull(member)) {
//            request.setAttribute("userId", member.getOpenId());
//            request.setAttribute("wxKey", member.getSessionKey());
//            request.setAttribute("member", member);
//
//            if (CommonUtils.isNotNull(member.getStatus()) && MemberStatus.REGISTERED.code.compareTo(member.getStatus()) == 0) {
//                request.setAttribute("memberId", member.getMemberId());
//            } else {
//                request.setAttribute("memberId", "");
//            }
//            tokenManager.refreshUserToken(token);
//        } else {
//            throw new AuthException(unauthorizedErrorMessage);
//        }
        return true;
    }
}
